from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.views.generic.list_detail import object_list, object_detail
from django.views.generic.create_update import  delete_object
from django.core.urlresolvers import reverse
from models import Category, Thread
from forms import ThreadForm, CategoryForm, AdminCategoryForm, AdminThreadForm
from userprofile.models import UserProfile
from django.contrib.auth.decorators import login_required, permission_required
#from threadedcomments.forms import ThreadedCommentForm

def admin_processor(request):
    return {'is_privileged':UserProfile.objects.is_privileged(request.user)}

processors = (admin_processor,)

def _get_pagination(request):
    # Attempt to get for pagination preference.
    # Otherwise, return the default of 20.
    try:
        profile = UserProfile.objects.get(user = request.user)
        return profile.pagination_preference
    except UserProfile.DoesNotExist:
        return 20



def category_list(request):
    return object_list(
        request,
        queryset = Category.objects.all(),
        template_object_name = 'category',
        paginate_by = _get_pagination(request),
        context_processors = processors
    )

#def category_create(request):
    #is_priveleged = UserProfile.object.is_privileged(request.user)
    #form = CategoryForm(request.user, request.POST or None)
    #if form.is_valid() and ( not is_privileged() or Admin:
        #category = form.save()
        #return HttpResponseRedirect(reverse('tf_category',kwargs={'slug':category.slug}))
    #return render_to_response('threadedforum/category_create.html',{'form':form},context_instance=RequestContext(request,{},processors))
#category_create = login_required(permission_required('add_category',login_url=reverse('tf_denied'))(category_create))
#category_create = login_required(category_create)

def category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return object_list(
        request,
        queryset = category.thread_set.all(),
        template_object_name = "thread",
        paginate_by = _get_pagination(request),
        extra_context = {'category_slug':slug,'category_name':category.name},
        context_processors = processors
    )

def category_delete(request, slug):
     return delete_object(
        model=Category,
        slug_field='slug',
        slug=slug,
        post_delete_redirect= reverse('tf_categories'),
        context_processors = processors
     )
#category_delete = login_required(permission_required('delete_category',login_url=reverse('tf_denied'))(category_create))
category_delete = login_required(category_delete)

def category_create_or_update(request, slug=None):
    is_privileged = UserProfile.objects.is_privileged(request.user)
    response = {}
    if not slug:
        category = Category()
    else:
        category = get_object_or_404(Category, slug=slug)
    if not request.POST:
        form = CategoryForm(instance=category)
        if is_privileged:
            admin_form = AdminCategoryForm(instance=category)
    else:
        form = CategoryForm(request.POST)
        if is_privileged:
            admin_form = AdminCategoryForm(request.POST)
    response.update({'form':form})
    if is_privileged:
        response.update({'admin_form':admin_form})
    if form.is_valid() and (not is_privileged or admin_form.is_valid()):
        for field in form.cleaned_data:
            setattr(category,field,form.cleaned_data[field])
        if is_privileged:
            for field in admin_form.cleaned_data:
                setattr(category,field,admin_form.cleaned_data[field])
        if request.POST.has_key('preview'):
            response.update({'category':category})
            return render_to_response(  "threadedforum/category_create.html",
                                        response, 
                                        context_instance=RequestContext(request,{},processors)
                                     )
        category.save()
        return HttpResponseRedirect(reverse('tf_category',kwargs={'slug':slug}))
    return render_to_response('threadedforum/category_create.html',response ,context_instance=RequestContext(request,{},processors))
category_create_or_update = login_required(category_create_or_update)


def thread_create_or_update(request,category_slug,object_id=None):
    is_privileged = UserProfile.objects.is_privileged(request.user)
    category = get_object_or_404(Category, slug=category_slug)
    if not object_id:
        thread = Thread()
    else:
        thread = Thread.objects.get(pk=object_id)
    if not request.POST:
        form = ThreadForm(instance=thread)
        if is_privileged:
            admin_form = AdminThreadForm(instance=thread)
    else:
        form = ThreadForm(request.POST)
        if is_privileged:
            admin_form = AdminThreadForm(request.POST)
    response = {'form':form}
    if is_privileged:
        response.update({'admin_form':admin_form})
    if form.is_valid() and (not is_privileged or admin_form.is_valid()):
        for field in form.cleaned_data:
            setattr(thread,field,form.cleaned_data[field])
        if is_privileged:
            for field in admin_form.cleaned_data:
                setattr(thread,field,admin_form.cleaned_data[field])
        if not hasattr(thread,'user'):
            thread.user = request.user
        thread.category = category
        if request.POST.has_key('preview'):
            response.update({'thread':thread})
            return render_to_response("threadedforum/thread_create.html",response, context_instance=RequestContext(request,{},processors))
        thread.save()
        return HttpResponseRedirect(reverse('tf_thread', kwargs={'category_slug':category_slug,'object_id':thread.pk}))
    return render_to_response("threadedforum/thread_create.html",response, context_instance=RequestContext(request,{},processors))

#thread_create = permission_required('add_thread',login_url=reverse('tf_denied'))(thread_create)
thread_create_or_update = login_required(thread_create_or_update)

def thread(request, category_slug, object_id):
    return object_detail(
        request,
        queryset = Thread.objects.filter(id = object_id),
        object_id = object_id,
        template_object_name = "thread",
        extra_context = {'category_slug' : category_slug},
        context_processors = processors
    )

def thread_delete(request, category_slug, object_id):
    return delete_object(
        request,
        model=Thread,
        object_id=object_id,
        post_delete_redirect=reverse('tf_category' , kwargs={'slug':category_slug}),
        extra_context={'category_slug':category_slug,'object_id':object_id},
        context_processors = processors
    )
#thread_delete = login_required(permission_required('delete_thread',login_url=reverse('tf_denied'))(thread_create))
thread_delete = login_required(thread_delete)
